package top.wintp.juhedatademo.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.google.gson.Gson;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import top.wintp.juhedatademo.R;
import top.wintp.juhedatademo.activity.ShowUrlActivity;
import top.wintp.juhedatademo.adapter.NewsListAdapter;
import top.wintp.juhedatademo.entity.NewsInfo;
import top.wintp.juhedatademo.global.ConstantValues;


/**
 * Created by Administrator on 2017/9/5 0005.
 * email: apk2sf@163.com
 * QQ：337081267
 */

public class BaseFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
    /**
     * TITLE的标识
     */
    public static final String TITLE = "title";
    public static final String TYPE = "type";

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {

        }
    };

    /**
     * Fragment的标题
     */
    private String mTitle;

    /**
     * 基本的View
     */
    protected View mBaseView;
    protected Context mContext;
    /**
     * type
     */
    private String mType;
    private SwipeRefreshLayout mSrf_refresh;
    private ListView mLv_list;

    public BaseFragment() {
    }


    /**
     * 获取BaseFragment的子类的对象
     *
     * @param clazz
     * @param title
     * @param <T>
     * @return
     */
    public static <T extends BaseFragment> T newInstance(Class<T> clazz, String title) {
        T fragment = null;
        try {
            fragment = clazz.newInstance();

            Bundle bundle = new Bundle();

            bundle.putString(BaseFragment.TITLE, title);
            String type = clazz.getSimpleName().split("Fragment")[0].toLowerCase();

            bundle.putString(BaseFragment.TYPE, type);

            fragment.setArguments(bundle);

            Log.e("BaseFragment", "BaseFragment newInstance()" + title);

        } catch (Exception e) {
        }

        return fragment;
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();

        Log.e("BaseFragment", "BaseFragment onCreate()getArguments" + getArguments());
        if (getArguments() != null) {
            mTitle = getArguments().getString(BaseFragment.TITLE);
            mType = getArguments().getString(BaseFragment.TYPE);
            Log.e("BaseFragment", "BaseFragment onCreate()" + mTitle);
        }

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBaseView = inflater.inflate(R.layout.fragment_base, container, false);

        return mBaseView;
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        initView();
    }

    public void initView() {
        mSrf_refresh = mBaseView.findViewById(R.id.srf_refresh);
        mLv_list = mBaseView.findViewById(R.id.lv_list);

        mSrf_refresh.setOnRefreshListener(this);
        initData();
    }

    private void initData() {
        String url = ConstantValues.NEWS_ROOT + "?type=" + mType + "&key=" + ConstantValues.JUHE_APP_KEY;
        RequestParams entity = new RequestParams(url);

        Log.e("BaseFragment", "BaseFragment initData()" + url);
        x.http().get(entity, new Callback.CommonCallback<String>() {
            public String result;

            @Override
            public void onSuccess(String result) {
                this.result = result;
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.e("BaseFragment", "BaseFragment onError()" + ex.getMessage());
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                if (!TextUtils.isEmpty(result)) {
                    progressData(result);
                }
            }
        });
    }

    /**
     * 解析json
     *
     * @param result
     */
    private void progressData(String result) {
        //Log.e("BaseFragment", "BaseFragment progressData()" + result);

        Gson gson = new Gson();
        final NewsInfo newsInfo = gson.fromJson(result, NewsInfo.class);

        if (newsInfo.getError_code() != ConstantValues.ERROR_CODE) {
            Toast.makeText(mContext, newsInfo.getReason(), Toast.LENGTH_SHORT).show();
            return;
        }

        //说明没有问题
        NewsListAdapter newsListAdapter = new NewsListAdapter(newsInfo.getResult().getData());
        mLv_list.setAdapter(newsListAdapter);

        mLv_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(parent.getContext(), ShowUrlActivity.class);
                intent.putExtra("url", newsInfo.getResult().getData().get(position).getUrl());

                startActivity(intent);
            }
        });

    }

    public String getTitle() {
        return getArguments().getString(BaseFragment.TITLE);
    }

    @Override
    public void onRefresh() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(mContext, "下拉刷新", Toast.LENGTH_SHORT).show();
                mSrf_refresh.setRefreshing(false);
            }
        }, 1000);
    }
}
